package com.mark.org.service.impl;

import com.mark.basic.service.Impl.BaseServiceImpl;
import com.mark.basic.util.MD5Utils;
import com.mark.basic.util.StrUtils;
import com.mark.org.domain.Employee;
import com.mark.org.mapper.EmployeeMapper;
import com.mark.org.service.IEmployeeService;
import com.mark.user.domain.Logininfo;
import com.mark.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 我们在CUD employee表的时候，需要级联操作logininfo，所以我们需要复写 save update  remove
     */

    @Override
    public void add(Employee employee) {
       initEmployee(employee);
       Logininfo logininfo =employee2loginInfo(employee);
       logininfoMapper.add(logininfo);
       employee.setLogininfo_id(logininfo.getId());
       employeeMapper.add(employee);
       initRelationTable(employee);
    }

    private void initRelationTable(Employee employee) {
        // 移除历史数据
        employeeMapper.removeEmployeeRole(employee.getId());
        // 添加数据
        employeeMapper.saveEmployeeRole(employee.getId(),employee.getRoles());
    }

    private Logininfo employee2loginInfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(0); // 设置类型 0代表员工
        return logininfo;
    }

    private void initEmployee(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        String password = MD5Utils.encrypByMd5(employee + salt);
        employee.setSalt(salt);
        employee.setPassword(password);
    }
}